<template>
  <ViewLayout
    ref="layout"
    size="small"
    class="no-bottom-border no-pad"
    :condition-form-props="{size: 'small',buttonSize: 'small',submitIcon: 'ri-search-line', resetIcon: 'ri-brush-3-line'}"
    condition-form-layout="flex"
    :configs="configs"
    :config-tree-props="configTreeProps"
    @gridOperation="handleGridOperation"
    @nodeClick="nodeClick"
    :has-add="false"
    :has-batch-remove="false"
  >
    <BKModal
      v-model="roleModalVisible"
      :title="roleModalTitle"
      width="500"
      height="80%"
    >
      <el-container>
        <el-main>
          <div class="p-a-mini full-height">
            <BKTable
              :loading="loadingRoles"
              ref="roleTable"
              size="mini"
              has-checkbox
              :has-pager="false"
              :data="roleList"
              :columns="roleModalTitle === '设置系统模块（统一门户）' ? menuColumns : roleColumns"
              :checkbox-config="{trigger:'row'}"
            />
          </div>
        </el-main>
        <el-footer style="height: auto;">
          <div class="p-b-mini ta-c">
            <el-button @click="resetRoles">
              重置
            </el-button>
            <el-button
              type="primary"
              @click="confirm"
            >
              保存
            </el-button>
          </div>
        </el-footer>
      </el-container>
    </BKModal>
    <BKModal
      title="重置密码"
      v-model="passwordModalVisible"
    >
      <div
        class="p-a-mini full-height"
        style="padding-bottom: 0;"
      >
        <BKForm
          :rules="passwordFormRules"
          :items="passwordFormItems"
          @reset="password=''"
          @submit="handleSubmitPassword"
        >
          <template #password>
            <BKPassword
              ref="password"
              v-model="password"
            />
          </template>
        </BKForm>
      </div>
    </BKModal>
    <BKModal
      v-model="visible"
      title="查看授权菜单"
      width="500"
      height="80%"
    >
      <ConfigTree
        :configs="treeConfigs"
        :tree-query-params="treeQueryParams"
        :has-add="false"
      />
    </BKModal>
    <template #leftTreeBehind>
      <div class="xj-content">
        <vxe-checkbox
          v-model="bhxjVal"
          checked-value="1"
          unchecked-value="0"
          @change="refreshList"
        >
          包含下级
        </vxe-checkbox>
      </div>
    </template>
  </ViewLayout>
</template>

<script>
import request from '@/utils/request'

const appId = 'watf'
const bzCode = 'WATF'

export default {
  name: 'User',
  components: {
    ViewLayout: () => import('../../../../../../../bk-web-foundation/src/views/skeleton/components/view-layout.vue')
  },
  data () {
    const validatePass = (rule, value, callback) => {
      if (this.password === '') {
        callback(new Error('请输入新密码'))
      } else if (!this.$refs.password.validate()) {
        callback(new Error('请按规则输入密码'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      configTreeProps: {
        nodeParam: this.$store.state.user.userInfo.DEPT_ID
      },
      treeConfigs: {
        appId: 'YSJC',
        bzCode: 'YSJC',
        treeConfigId: 'YSJC_YHGL_CDXS_TREE'
      },
      configs: {
        tree: {
          url: '/ysjc/user/initQxshInfo',
          dictionaryKeys: ['DIC_WATF_B_UP_D'],
          // activeNodeKey: this.$store.state.user.userInfo.DEPT_ID,
          includeSelf: true,
          canSortItem: false,
          sortKeyProps: { id: 'DEPT_ID', fid: 'PARENT_ID', order: 'ORDER_NUM' },
          hasIcon: false,
          canSwitchBzCode: false,
          appId,
          bzCode,
          async: false,
          treeConfigId: 'DEPT_TREE',
          // menuConfig: [
          //   { title: '新增部门', visible: (data) => this.checkTreeNodeVisible(data, false, 'system:dept:add'), handler: 'addManagementNode' },
          //   { title: '编辑部门', visible: (data) => this.checkTreeNodeVisible(data, false, 'system:dept:edit'), handler: 'editManagementNode' },
          //   { title: '删除部门', visible: (data) => this.checkTreeNodeVisible(data, true, 'system:dept:remove'), handler: 'removeManagementNode' }
          // ],
          defaultExpandAll: false,
          management: {
            module: '部门',
            metaSet: 'WATF_B_SYS_DEPT',
            parentNodeProps: { PARENT_ID: 'id' },
            primaryKeyProps: { DEPT_ID: 'id' },
            formPresetProcessor: this.formPresetProcessor
          },
          onDraggableMove: this.onDraggableMove,
          hasAdd: false
        },
        grid: {
          checkGridParent: this.checkGridParent,
          module: '用户',
          appId,
          bzCode,
          metaSet: 'WATF_B_SYS_USER',
          parentNodeProps: { DEPT_ID: 'id' },
          operationWidth: 170,
          noOperation: true,
          prepandOperations: [
            { text: '设置角色', operationName: 'setRole', class: 'ri-user-settings-line', authCode: 'system:user:auth' },
            { text: '重置密码', operationName: 'resetPassword', class: 'ri-restart-line', authCode: 'system:user:resetPwd' },
            { text: '解锁用户', operationName: 'unlock', class: 'ri-lock-unlock-line', authCode: 'system:user:unlock' }
          ],
          buttonPermissions: {
            add: 'system:user:add',
            edit: 'system:user:edit',
            export: 'system:user:export',
            remove: 'system:user:remove'
          },
          formItemProcessor: this.formItemProcessor,
          beforeFormSubmit: this.beforeFormSubmit,
          modal: {
            width: 440
          },
          defaultQueryParamsProcessor: this.defaultQueryParamsProcessor,
          gridMethod: 'selectwatfWatfWatfBSysUserOrderByDeptOrderNum',
          afterFetchColumns: this.afterFetchColumns
        }
      },
      roleModalVisible: false,
      roleModalTitle: '',
      roleColumns: [
        { title: '角色名称', field: 'ROLE_NAME', width: 120 },
        { title: '角色编码', field: 'ROLE_KEY' }
      ],
      menuColumns: [
        { title: '应用名称', field: 'INTRO' }
      ],
      roleList: [],
      loadingRoles: false,
      passwordModalVisible: false,
      passwordFormRules: {
        newPassword: [{ validator: validatePass, trigger: 'blur' }],
        repeatPassword: [{ validator: validatePass2, trigger: 'blur' }]
      },
      passwordFormItems: [
        { label: '新密码', field: 'newPassword', slot: 'password' },
        { type: 'input', label: '确认密码', field: 'repeatPassword', props: { showPassword: true } }
      ],
      password: '',
      bhxjVal: '0',
      treeQueryParams: { bzCode: 'YSJC' },
      visible: false
    }
  },
  methods: {
    refreshList () {
      if (!this.currentNode) return
      this.$refs.layout.refreshGrid()
    },
    formPresetProcessor (data, isEdit) {
      if (!isEdit) {
        data.PARENT_ID = this.$refs.layout.$refs.tree?.currentManagementNode?.id || 'ROOT'
      }
      return data
    },
    checkGridParent (parent) {
      return true
    },
    handleGridOperation (operationName, row) {
      this[operationName](row)
    },
    afterFetchColumns (columns) {
      columns.push({
        title: '操作',
        width: 100,
        fixed: 'right',
        slots: {
          default: ({ row }) => {
            return [
              <div class="operation-icon-buttons">
                <i vAuth={['system:user:auth']} class="ri-user-settings-line" title="设置角色" onClick={() => this.setRole(row)}></i>
                <i vAuth={['system:user:auth']} class="ri-user-star-line" title="设置系统模块（统一门户）" onClick={() => this.setMenuRole(row)}></i>
                <i class="ri-eye-line" title="查看菜单" onClick={() => this.openMenuTree(row)}></i>
              </div>
            ]
          }
        }
      })
      return columns
    },
    openMenuTree (row) {
      this.treeQueryParams = Object.assign(this.treeQueryParams, { USER_ID: row.USER_ID })
      this.visible = true
    },
    async setMenuRole (row) {
      this.currentRow = row
      this.roleModalTitle = '设置系统模块（统一门户）'
      this.roleModalVisible = true
      this.loadingRoles = true
      const data = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'SYS_CLIENT',
        methodCode: 'select',
        methodParams: { queryParam: { APP_SHOW: 1 } }
      })
      this.roleList = data.rows
      this.loadingRoles = false
      request.post('/SingleTable/curd', {
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_LBMH_CLIENT',
        methodCode: 'select',
        methodParams: JSON.stringify({
          queryParam: {
            USER_ID: row.USER_ID
          }
        })
      }).then((resData) => {
        this.currentRoles = resData.rows.map(r => {
          return this.roleList.find(role => role.ID === r.APPID)
        })
        this.$refs.roleTable.setCheckboxRow(this.currentRoles, true)
      })
    },
    async setRole (row) {
      this.currentRow = row
      this.roleModalTitle = `设置角色—${row.NICK_NAME || row.USER_NAME || '匿名用户'}`
      this.roleModalVisible = true
      this.loadingRoles = true
      const data = await request.post('/SingleTable/curd', {
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_PW_ROLE',
        methodCode: 'selectCalysjcYsjcYsqjcPwUserRolesList'
      })
      this.roleList = data.rows
      this.loadingRoles = false
      request.post('/SingleTable/curd', {
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_PW_USER_ROLE',
        methodCode: 'select',
        methodParams: JSON.stringify({
          queryParam: {
            USER_ID: row.USER_ID
          }
        })
      }).then((resData) => {
        this.currentRoles = resData.rows.map(r => {
          return this.roleList.find(role => role.ROLE_ID === r.ROLE_ID)
        })
        this.$refs.roleTable.setCheckboxRow(this.currentRoles, true)
      })
    },
    resetRoles () {
      this.$refs.roleTable.clearCheckboxRow()
      this.$refs.roleTable.setCheckboxRow(this.currentRoles, true)
    },
    async confirm () {
      const rows = this.$refs.roleTable.getCheckboxRecords()
      if (this.roleModalTitle === '设置系统模块（统一门户）') {
        await request.post('/SingleTable/curd', {
          appId: 'YSJC',
          bzCode: 'YSJC',
          metaSet: 'YSQJC_LBMH_CLIENT',
          methodCode: 'override',
          methodParams: JSON.stringify({
            deleteParam: {
              USER_ID: this.currentRow.USER_ID
            },
            batchParam: rows.map(r => {
              return {
                USER_ID: this.currentRow.USER_ID,
                APPID: r.ID,
                IS_VALID: '1'
              }
            })
          })
        })
        this.$message.success('操作成功！')
        this.roleModalVisible = false
        return
      }
      if (!rows.length) {
        return this.$message.error('请先勾选角色！')
      }
      // await request.post('/SingleTable/curd', {
      //   appId: 'YSJC',
      //   bzCode: 'YSJC',
      //   metaSet: 'YSQJC_PW_USER_ROLE',
      //   methodCode: 'override',
      //   methodParams: JSON.stringify({
      //     deleteParam: {
      //       USER_ID: this.currentRow.USER_ID
      //     },
      //     batchParam: rows.map(r => {
      //       return {
      //         USER_ID: this.currentRow.USER_ID,
      //         ROLE_ID: r.ROLE_ID
      //       }
      //     })
      //   })
      // })
      await this.$request.post('/ysjc/user/initUserMenu', {
        USER_ID: this.currentRow.USER_ID,
        ROLE_ID: rows.map(item => item.ROLE_ID).join(',')
      })
      this.$message.success('操作成功！')
      this.roleModalVisible = false
    },
    resetPassword (row) {
      this.currentRow = row
      this.passwordModalVisible = true
    },
    async handleSubmitPassword () {
      await request.post('/user/resetPwd', {
        newPassword: this.password,
        userId: this.currentRow.USER_ID
      })
      this.passwordModalVisible = false
      this.$message.success('操作成功！')
    },
    unlock (row) {
      request.get(`/unlock/${row.USER_NAME}`).then(() => {
        this.$message.success('操作成功！')
      })
    },
    checkTreeNodeVisible (node, checkLeaf, authCode) {
      if (this.$permission) {
        if (!this.$permission.hasPermission(authCode)) {
          return false
        }
      }
      if (checkLeaf) {
        return node.isLeaf && node.att1 !== '1'
      }
      return node.att1 !== '1'
    },
    onDraggableMove (data) {
      // 只允许改变顺序，不能跨级拖拽
      return data.draggedContext?.element?.fid === data.relatedContext?.element?.fid
    },
    formItemProcessor ({ items, rules }) {
      for (const item of items) {
        if (item.field === 'USER_NAME') {
          item.props.placeholder = '请输入用户账号，推荐使用手机号'
        } else if (item.field === 'DEPT_ID') {
          item.props.rootKey = this.$store.state.user.userInfo.DEPT_ID
        }
      }
      return { items, rules }
    },
    beforeFormSubmit (data, isEdit) {
      const params = JSON.parse(data.methodParams)
      data.methodParams = JSON.stringify(params)
      return data
    },
    levelOrder (root) {
      const res = []; const queue = []
      queue.push(root)
      if (root === null) {
        return res
      }
      while (queue.length !== 0) {
        const length = queue.length
        for (let i = 0; i < length; i++) {
          const node = queue.shift()
          res.push(node.id)
          for (let n = 0; n < node.children?.length; n++) {
            if (node.children[n]) {
              queue.push(node.children[n])
            }
          }
        }
      }
      return res
    },
    nodeClick (data) {
      this.currentNode = data
    },
    defaultQueryParamsProcessor (params) {
      const methodParams = JSON.parse(params.methodParams)
      if (this.bhxjVal === '1') {
        const isLeaf = this.currentNode.isLeaf
        const leafIds = isLeaf ? [] : this.levelOrder(this.currentNode)
        methodParams.simpleQueryParam.push({
          field: 'DEPT_ID',
          value: isLeaf ? this.currentNode.id : leafIds.join(','),
          fieldValueRel: isLeaf ? 'like' : 'in'
        })
        methodParams.queryParam = {}
        params.methodParams = JSON.stringify(methodParams)
      } else {
        methodParams.queryParam = { DEPT_ID: this.currentNode.id }
        params.methodParams = JSON.stringify(methodParams)
      }
      return params
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .vxe-toolbar {
    padding: 10px 0 !important;

    .toolbar-left-container .el-button {
      margin-bottom: 0 !important;
    }
  }
}

.no-pad {
  padding: 0;

  ::v-deep .mc-side-area {
    .bk-tree-wrapper {
      margin-left: 23px;
    }
  }
}

::v-deep .mc-side-area {
  overflow: hidden;
}

::v-deep .xj-content {
  position: absolute;
  left: -9px;
  top: 40%;
  width: 36px;
  z-index: 8;
  border: 1px solid #c7deee;
  border-radius: 16px;
  background-color: #f5f7f9;
  padding: 8px;
  transform: translateY(-50%);

  .vxe-checkbox {
    text-align: center;
    display: flex;
    flex-direction: column;
  }

  .vxe-checkbox--icon {
    position: relative;
    display: block;
    margin: 0 auto;
    margin-left: 2px;
  }

  .vxe-checkbox--icon::before {
    height: 0.64em;
    width: 0.32em;
    left: 50%;
    top: 40%;
    border: 2px solid #fff;
    border-left: 0;
    border-top: 0;
    transform: translate(-50%, -50%) rotate(45deg);
  }

  .vxe-checkbox--label {
    line-height: 16px;
    display: block !important;
    font-size: 14px;
    width: 20px;
    padding-bottom: 6px;
    padding-top: 3px;
    min-height: 50px;
    white-space: normal !important;
    padding-left: 0 !important;
  }
}
</style>
